package Test.CyclicBarrierDemo;

import java.util.Random;
import java.util.concurrent.*;

/**
 * 模拟LOL加载的场景
 * 需要等待所有玩家全部加载完成之后再进入游戏
 *
 * @author handsomePot
 * @date 2022/1/9 13:40
 */
public class BaseDemo {


    public static void main(String[] args) {


        String[] nameList = {"中单卡萨丁", "上单诺手", "打野赵信", "ad卡莎", "辅助泰坦"};

        //参数5 表示有5个线程参与
        CyclicBarrier barrier = new CyclicBarrier(5);

        ExecutorService service = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 5; i++) {
            service.execute(new Player(nameList[i], barrier));
        }

        service.shutdown();
    }


    public static class Player implements Runnable {
        private String name;

        private CyclicBarrier cyclicBarrier;

        public Player(String name, CyclicBarrier cyclicBarrier) {
            this.name = name;
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            //在这里模拟   玩家加载及等待的情况
            try {
                TimeUnit.SECONDS.sleep(new Random().nextInt(10));
                System.out.println(name + "： 已经加载100%  加载完成!");
                cyclicBarrier.await();
                //所有 玩家加载完成之后  会唤醒其他阻塞的线程
                System.out.println(name + "： 全军出击!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }


        }
    }

}
